package com.wy.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.sun.deploy.net.URLEncoder;
import com.wy.dao.User;
import com.wy.mapper.UserMapper;
import com.wy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * @author 33117
 * @version 1.0
 * @data 2025/2/27 17:55
 */
@RestController
@RequestMapping("excel")
public class ExcelController {
    @Autowired
    public UserService userService;
    @Autowired
    public UserMapper userMapper;

    /*
     * 导出Excel
     */
    @GetMapping("export")
    public void export(HttpServletResponse response) throws Exception {
        // 1. 获取数据
        List<User> list = userMapper.selectList(null);
        // 2. 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
        String fileName = URLEncoder.encode("员工信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
        // 3. 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        try (ExcelWriter writer = ExcelUtil.getWriter(true)) {
            // 4. 设置中文表头
            writer.addHeaderAlias("name", "名字");
            // 4.1 如果只导出自定义字段
            writer.setOnlyAlias(true);
            // 5. 写出数据到输出流
            writer.write(list, true);
            // 6. 刷新并关闭流
            writer.flush(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    /*
     * 导入
     */
    @PostMapping("import")
    public String importDate(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            // 1. 构建 ExcelReader
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            // 2. 设置列别名
            reader.addHeaderAlias("名字", "name");
            // 3. 读取 Excel 数据
            List<User> list = reader.readAll(User.class);
            // 4. 入库
            for (User user : list) {
                userMapper.insert(user);
            }
            return "导入成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败：" + e.getMessage();
        }
    }
}
